<?php		
/**
 * API Demonstration code for RPX.  Runs only on PHP 5.  Requires CURL
 * and DOM XML parsing support.
 *
 * Instantiate RPX with your API key and RPX API URL.  The public
 * interface returns DOMDocument objects to be parsed by your
 * application.  You can choose to request JSON data, which requires a
 * different parser not available on most PHP installations.
 *
 * The demonstration API throws APIException on HTTP or parsing error.
 *
 * $rpx = new RPX("1422262b85e296164f95913b9efc0d8316754b35",
 *                "http://EXAMPLE.rpxnow.com/");
 */
include_once('Smarty.class.php');
$main_smarty = new Smarty;
include('config.php');
include(mnminclude.'html1.php');
include(mnminclude.'link.php');
include(mnminclude.'smartyvariables.php');
include_once(mnminclude.'user.php');

if(isset($_GET["token"]))
{
	$token = $_GET["token"];

}

$rpx = new RPX("8972a5b9f2f3821cfe6f5650e1d6b8b472133356", "https://fashion-voices.rpxnow.com");
$doc = $rpx->auth_info($token);
//$root = $doc->childNodes->item(0);
//$node = $root->attributes->getNamedItem('stat');
//$root->childNodes->getNamedItem('stat');
//$profiles  = $doc->getElementsByTagName("profile");
//$profile = $profiles->item(0)->nodeValue;

$item = $doc->getElementsByTagName("displayName");
$displayName = $item->item(0)->nodeValue;

$item = $doc->getElementsByTagName("email");
$email = $item->item(0)->nodeValue;

$item = $doc->getElementsByTagName("identifier");
$identifier = $item->item(0)->nodeValue;

$item = $doc->getElementsByTagName("preferredUsername");
$preferredUsername = $item->item(0)->nodeValue;

$item = $doc->getElementsByTagName("providerName");
$providerName = $item->item(0)->nodeValue;

$item = $doc->getElementsByTagName("verifiedEmail");
$verifiedEmail = $item->item(0)->nodeValue;

$item = $doc->getElementsByTagName("primaryKey");
$primayKey = $item->item(0)->nodeValue;
if($primayKey == '')
{
	// create user
	$username = 'user'.time();
	while (user_exists($username))
	{
		$username = 'user'.time();
	}		

	$user = new User();
	$user->username = $username;
	if($user->Create()){
		$user->read('short');	
		$rpx->map($identifier, $user->id);
	}	
	else
	{
		exit(1);
	}
		
}
else
{	
	$user = new User($primayKey);		

}


$registration_details = array(
	'username' => $user->username,
	'password' => '',
	'email' => '',
	'id' => $user->id
);

check_actions('register_success_pre_redirect', $registration_details);
global $current_user;
$current_user->Authenticate($user->username, '', false);
echo pligg_validate();
echo my_base_url.my_pligg_base.'/register_complete.php?user='.$user->username;
if(pligg_validate() == 1){
	header('Location: '.my_base_url.my_pligg_base.'/register_complete.php?user='.$user->username);
} else {
	header('Location: ' . getmyurl('user', $user->username));
}

echo "$primayKey, $displayName, $email, $identifier, $preferredUsername, $providerName, $verifiedEmail\n";


class APIException extends Exception {}

class RPX {
    var $api_key = null;
    var $base_url = null;
    var $format = "xml";
    var $response_body = "";

    function RPX($api_key, $base_url) {
        while ($base_url[strlen($base_url) - 1] == "/") {
            $base_url = substr($base_url, 0, strlen($base_url) - 1);
        }

        $this->api_key = $api_key;
        $this->base_url = $base_url;
    }

    /*
     * Performs the 'auth_info' API call to retrieve information about
     * an OpenID authentication response.  You'll need to inspect the
     * resulting DOMDocument to get information about the response.
     * See the API documentation for details.
     *
     * https://rpxnow.com/docs
     */
    public function auth_info($token) {
        return $this->apiCall("auth_info", array("token" => $token));
    }

    /*
     * Returns an array of identifier mappings for the specified
     * primary key.
     */
    public function mappings($primary_key) {
        $doc = $this->apiCall(
             "mappings", array("primaryKey" => $primary_key));

        $identifiers = array();

        $xpath = new DOMXPath($doc);
        $nodes = $xpath->query("/rsp/identifiers/identifier");

        foreach ($nodes as $identifier_node) {
          $identifiers[] = $identifier_node->textContent;
        }

        return $identifiers;
    }

    /*
     * Maps an identifier to a primary key from your application.
     * Returns null.
     */
    public function map($identifier, $primary_key) {
        $this->apiCall("map", array("primaryKey" => $primary_key,
                                    "identifier" => $identifier));
    }

    /*
     * Removes a mapping for an identifier and primary key.  Returns
     * null.
     */
    public function unmap($identifier, $primary_key) {
        $this->apiCall("unmap", array(
            "primaryKey" => $primary_key,
            "identifier" => $identifier));
    }

    /*
     * Performs an API call using the specified name and arguments
     * array.  Automatically adds your API key to the request and
     * requests an XML response.  Returns a DOMDocument or raises
     * APIException.
     */
    private function apiCall($method_name, $partial_query) {
        $partial_query["format"] = $this->format;
        $partial_query["apiKey"] = $this->api_key;

        $query_str = "";
        foreach ($partial_query as $k => $v) {
            if (strlen($query_str) > 0) {
                $query_str .= "&";
            }

            $query_str .= urlencode($k);
            $query_str .= "=";
            $query_str .= urlencode($v);
        }

        $url = $this->base_url . "/api/v2/" . $method_name;
		//echo $url;
        $response_body = $this->_post($url, $query_str);
		//echo $response_body;
		
        $api_response = $this->_parse($response_body);
        $status = $this->_getMessageStatus($api_response);

        if ($status != 'ok') {
            throw new APIException(
              sprintf("API status was not 'ok', got '%s' instead", $status));
        }

        return $api_response;
    }

    private function _getMessageStatus($parsed_response) {
        $root = $parsed_response->childNodes->item(0);
        $node = $root->attributes->getNamedItem('stat');
        return $node->value;
    }

    private function _resetPostData() {
        $this->response_data = "";
    }

    private function _writeResponseData($curl_handle, $raw) {
        $this->response_data .= $raw;
        return strlen($raw);
    }

    private function _post($url, $post_data) {
        $this->_resetPostData();

        $curl = curl_init();

        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_WRITEFUNCTION,
                    array(&$this, "_writeResponseData"));

        curl_exec($curl);

        $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        if (!$code) {
            throw new APIException(
              sprintf("Error performing HTTP request: %s", curl_error($curl)));
        }

        $response_body = $this->response_data;		
        $this->_resetPostData();
        curl_close($curl);

        return $response_body;
    }

    private function _parse($raw) {
        $doc = new DOMDocument;

        if (!$doc->loadXML($raw)) {
            throw new APIException("Error parsing XML response");
        }

        return $doc;
    }
}

/*
 * API methods that we can demonstrate from the command line.
 */
global $SUPPORTED_METHODS;
$SUPPORTED_METHODS = array("map", "unmap", "mappings");

/*
 * Print out usage information for this demo code.
 */
function usage() {
  global $SUPPORTED_METHODS;
  global $argv;

  print sprintf(
     "Usage: %s <API key> <RPX service URL> <%s> [param ...]\n",
     $argv[0], implode("|", $SUPPORTED_METHODS));

  print "API methods:\n";
  print "  map <identifier> <primary key>\n";
  print "  unmap <identifier> <primary key>\n";
  print "  mappings <primary key>\n";

  exit(1);
}

function main() {
  global $SUPPORTED_METHODS;
  global $argv;

  if (count($argv) < 3) {
    usage();
  }

  list(, $api_key, $base_url, $api_method) = $argv;

  if (!in_array($api_method, $SUPPORTED_METHODS)) {
    usage();
  }

  $rpx = new RPX($api_key, $base_url);
  $parameters = array_slice($argv, 4);

  try {
      $result = call_user_func_array(array($rpx, $api_method), $parameters);
  } catch (APIException $e) {
      print "Error encountered while trying to perform API request:\n";
      print $e->getMessage()."\n";
      exit(1);
  }

  if ($result !== null) {
    print sprintf("Result of '%s' API call:\n", $api_method);
    print_r($result);
  }
}

//main();

?>
